#include <stdio.h>
#include <string.h>

void transpose(char buff[32], short smps_short[16])
{
	int x, y;
	int smps[16];

	for (x = 0; x < 8; x++) {
		smps[x] = 0;
		
		for (y = 0; y < 16; y++)
			smps[x] |= ((buff[y * 2] & (1 << (7 - x))) >> (7 - x)) << (15 - y);
	}
	
	for (x = 0; x < 8; x++) {
		smps[x + 8] = 0;
		
		for (y = 0; y < 16; y++)
			smps[x + 8] |= ((buff[y * 2 + 1] & (1 << (7 - x))) >> (7 - x)) << (15 - y);
	}

	for (x = 0; x < 16; x++)
		smps_short[x] = (short) (smps[x] - 0x8000);
}

int main(int argc, char const *argv[])
{
	int i;
	FILE *stream[8];

	fprintf(stderr, "%s: fx2deserialize\n", argv[0]);

	if (argc != 2) {
		fprintf(stderr, "%s: usage: %s filename_base\n", argv[0], argv[0]);
		return 1;
	}

	for (i = 0; i < 8; i++) {
		char filename[32];
		if (i != 7)
			sprintf(filename, "%s_%d.raw", argv[1], i);
		else
			strcpy(filename, "/dev/stdout");
		stream[i] = fopen(filename, "w");

		if (!stream) {
			perror("fopen");
			return 0;
		}
	}

	char buffer[32];
	short samples[16];

	while (1) {
		if (fread(&(buffer[0]), 1, 1, stdin) == 0)
			break;

		if (buffer[0] & 0x80) {
			if (fread(buffer + 1, 1, 31, stdin) != 31)
				break;

			transpose(buffer, samples);

			for (i = 0; i < 8; i++) {
				if (!fwrite(&(samples[i]), sizeof(short), 1, stream[i])) {
					perror("fwrite");
					break;
				}

				if (!fwrite(&(samples[i + 8]), sizeof(short), 1, stream[i])) {
					perror("fwrite");
					break;
				}
			}
		} else {
			fprintf(stderr, "%s: out of sync\n", argv[0]);
		}
	}

	for (i = 0; i < 8; i++)
		fclose(stream[i]);

	return 0;
}
